package com.road.vast.springboot;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @Author 郭泽鹏
 * @Date 2020/7/31 14:34
 * @Version 1.0
 * @Description 模拟通过Shiro进行用户授权登录
 */
@SpringBootTest
public class ShiroTest02 {
    /**
     * 测试用户授权
     *      授权：用户登录
     *
     *      1.加载ini配置文件
     *      2.把数据源绑定到DefaultSecurityManager实例中
     *      3.把manager绑定到SecurityUtils
     *      4.从当前环境中构造subject对象
     *      5.构造shiro登录的数据
     *      6.创建令牌
     *      7.主体登录
     *      8.登录之后，完成授权
     */
    private DefaultSecurityManager manager;

//    @Before
    public void init(){
        //1.加载ini配置文件
        DefaultSecurityManager manager = new DefaultSecurityManager();
        IniRealm realm = new IniRealm("classpath:shiro-auth-02.ini");

        //2.把数据源绑定到DefaultSecurityManager实例中
        manager.setRealm(realm);

        //3.把manager绑定到SecurityUtils
        SecurityUtils.setSecurityManager(manager);
    }

    @Test
    public void testLogin(){
        this.init();
        //4.从当前环境中构造subject对象
        Subject subject = SecurityUtils.getSubject();

        //5.构造shiro登录的数据
        String username = "lisi";
        String password = "654321";

        //6.创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        //7.主体登录
        subject.login(token);

        //8.登录之后，完成授权
        //授权：检验当前登录用户是否具有操作权限，是否具有某个角色
        System.out.println(subject.hasRole("role1"));
        System.out.println(subject.isPermitted("user:save"));
    }
}
